<script setup lang="ts">
import type { PropType } from 'vue'
import type { IMethods, ITableDataSet } from '@/types'
import { computed, inject, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface TabItem {
  title: string
  path: string
  fullPath: string
  closable: boolean
}

const props = defineProps({
  mainData: {
    type: Object as PropType<ITableDataSet>,
    default: () => ({}),
  },
  remark: {
    default: 0,
  },
})

const route = useRoute()
const router = useRouter()

// 每页数量数组
const pageSizes = reactive([10, 20, 50, 100, 200, 300, 500, 1000, 2000, 3000, 5000, 10000])
const methods = inject<IMethods>('methods')

// 标签页数据
const tabs = ref<TabItem[]>([])
const contextMenuVisible = ref(false)
const contextMenuLeft = ref(0)
const contextMenuTop = ref(0)
const currentContextTab = ref<TabItem | null>(null)

// 监视页数 默认没有则添加
watch(() => props.mainData.form.rows, (val) => {
  if (val && !pageSizes.includes(val))
    pageSizes.push(val)
  pageSizes.sort((a, b) => a - b)
}, { immediate: true })

// 初始化标签页
onMounted(() => {
  initTabs()
  window.addEventListener('click', closeContextMenu)
})

onUnmounted(() => {
  window.removeEventListener('click', closeContextMenu)
})

// 路由变化时更新标签页
watch(() => route.fullPath, () => {
  addTab()
})

// 初始化标签页
function initTabs() {
  const homeTab = {
    title: '首页',
    path: '/home',
    fullPath: '/home',
    closable: false,
  }
  tabs.value = [homeTab]
  addTab()
}

// 添加标签页
function addTab() {
  const { meta, path, fullPath, name } = route
  if (!meta.noTab) {
    const tabExists = tabs.value.some(tab => tab.path === path)
    if (!tabExists && name) {
      tabs.value.push({
        title: meta.title as string || (name as string),
        path,
        fullPath,
        closable: path !== '/home',
      })
    }
  }
}

// 判断标签是否激活
function isActive(tab: TabItem) {
  return tab.path === route.path
}

// 标签点击事件
function handleTabClick(tab: TabItem) {
  router.push(tab.fullPath)
}

// 标签关闭事件
function handleTabClose(tab: TabItem) {
  const index = tabs.value.findIndex(item => item.path === tab.path)
  if (index !== -1) {
    // 如果关闭的是当前激活的标签，需要跳转到前一个标签
    if (isActive(tab)) {
      const prevTab = tabs.value[index - 1]
      if (prevTab) {
        router.push(prevTab.fullPath)
      }
    }
    tabs.value.splice(index, 1)
  }
}

// 打开右键菜单
function openContextMenu(e: MouseEvent, tab: TabItem) {
  contextMenuVisible.value = true
  contextMenuLeft.value = e.clientX
  contextMenuTop.value = e.clientY
  currentContextTab.value = tab
}

// 关闭右键菜单
function closeContextMenu() {
  contextMenuVisible.value = false
}

// 刷新当前标签页
function refreshTab() {
  if (currentContextTab.value) {
    router.replace({
      path: `/redirect${currentContextTab.value.fullPath}`,
    })
  }
  closeContextMenu()
}

// 关闭当前标签页
function closeCurrentTab() {
  if (currentContextTab.value) {
    handleTabClose(currentContextTab.value)
  }
  closeContextMenu()
}

// 关闭其他标签页
function closeOtherTabs() {
  if (currentContextTab.value) {
    tabs.value = tabs.value.filter(
      tab => !tab.closable || tab.path === currentContextTab.value?.path,
    )
    if (!isActive(currentContextTab.value)) {
      router.push(currentContextTab.value.fullPath)
    }
  }
  closeContextMenu()
}

// 关闭右侧标签页
function closeRightTabs() {
  if (currentContextTab.value) {
    const index = tabs.value.findIndex(
      tab => tab.path === currentContextTab.value?.path,
    )
    if (index !== -1) {
      tabs.value = tabs.value.slice(0, index + 1).concat(
        tabs.value.slice(index + 1).filter(tab => !tab.closable),
      )
    }
  }
  closeContextMenu()
}

// 关闭所有标签页
function closeAllTabs() {
  tabs.value = tabs.value.filter(tab => !tab.closable)
  router.push('/home')
  closeContextMenu()
}

// 分页变化事件
function handlePaginationChange() {
  methods?.search?.()
}

function handleSysIDClick() {
  // 这里可以添加SysID点击的逻辑
}
</script>

<template>
  <div class="toolbar flex-between">
    <div class="sysID items-center link" @click="handleSysIDClick">
      SysID:{{ mainData.ID }}
    </div>
    <slot name="default" />
    <el-pagination
      v-model:current-page="mainData.form.page" v-model:page-size="mainData.form.rows"
      :page-sizes="pageSizes" layout="sizes,prev, pager, next, jumper, total" :total="mainData.count"
      @size-change="handlePaginationChange" @current-change="handlePaginationChange"
    />
  </div>
</template>

<style scoped lang="scss">
.toolbar {
    width: 100%;
    padding: 10px 0;

    .sysID {
        height: 100%;
        font-size: 20px;
        cursor: pointer;
    }
}
</style>
